package com.heima.article.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.apis.ISearchClient;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.common.constants.ArticleConstants;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {
    @Autowired
    private ApArticleMapper apArticleMapper;

    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;

    @Autowired
    private ApArticleContentMapper apArticleContentMapper;

    @Autowired
    private ArticleFreemarkerService articleFreemarkerService;

    @Autowired
    private ISearchClient searchClient;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * TODO
     *      - 加载首页
     *
     * @param articleHomeDto 请求体参数
     * @param type           1为加载更多  2为加载最新
     * @return ResponseResult
     */
    @Override
    public ResponseResult load(ArticleHomeDto articleHomeDto, Integer type) {
        // 1.校验参数
        // 校验size
        Integer size = articleHomeDto.getSize();
        if (size == null || size == 0) {
            articleHomeDto.setSize(10);
        }
        // 校验频道
        String tag = articleHomeDto.getTag();
        if (StringUtils.isEmpty(tag)) {
            articleHomeDto.setTag("__all__");
        }
        // 校验时间
        if (articleHomeDto.getMinBehotTime() == null) {
            articleHomeDto.setMinBehotTime(new Date());
        }
        if (articleHomeDto.getMaxBehotTime() == null) {
            articleHomeDto.setMaxBehotTime(new Date());
        }
        // 2.查询数据
        articleHomeDto.setType(type);
        List<ApArticle> articleList = searchClient.load(articleHomeDto);
        // 3.封装结果返回
        return ResponseResult.okResult(articleList);
    }

    /**
     * 保存文章
     *
     * @param dto dto
     * @return ResponseResult
     */
    @Override
    @Transactional
    public ResponseResult save(ArticleDto dto) {
        ApArticle apArticle = null;
        // 1.参数校验
        if (dto == null || dto.getContent() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2.如果没有id保存
        if (dto.getId() == null) {
            // 保存文章
            apArticle = new ApArticle();
            BeanUtils.copyProperties(dto, apArticle);
            apArticleMapper.insert(apArticle);
            // 保存文章配置
            ApArticleConfig apArticleConfig = new ApArticleConfig(apArticle.getId());
            apArticleConfigMapper.insert(apArticleConfig);
            // 保存文章内容
            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setArticleId(apArticle.getId());
            apArticleContent.setContent(dto.getContent());
            apArticleContentMapper.insert(apArticleContent);
        } else {
            // 3.如果有新增
            apArticle = apArticleMapper.selectById(dto.getId());
            // 修改文章
            if (apArticle != null) {
                BeanUtils.copyProperties(dto, apArticle);
                apArticleMapper.updateById(apArticle);
            }
            // 修改文章内容
            ApArticleContent apArticleContent = apArticleContentMapper.selectOne(
                    Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, dto.getId()));
            if (apArticleContent != null) {
                apArticleContent.setContent(dto.getContent());
                apArticleContentMapper.updateById(apArticleContent);
            }
        }
        articleFreemarkerService.buildArticleToMinIO(apArticle, dto.getContent());
        // 4.返回文章id
        return ResponseResult.okResult(apArticle == null ? "" : apArticle.getId());
    }

    /**
     * 首页热点文章推送
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadArticle(ArticleHomeDto dto) {
        // 1.校验参数
        if (dto == null || dto.getTag() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2.获取redis中的热点文章集合
        String key = ArticleConstants.HOT_ARTICLE_FIRST_PAGE + dto.getTag();
        String hotArticleStr = redisTemplate.opsForValue().get(key);
        List<HotArticleVo> hotArticleVos = JSONArray.parseArray(hotArticleStr, HotArticleVo.class);
        // 3.返回结果
        return ResponseResult.okResult(hotArticleVos);
    }
}
